package com.vshop.auth.service;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.vshop.auth.api.ApiUserService;
import com.vshop.auth.api.event.UpdateLoginInfoEvent;
import com.vshop.framework.core.constant.Const;
import com.vshop.framework.core.domain.model.LoginUser;
import com.vshop.framework.core.spring.SpringContextUtil;
import com.vshop.framework.core.util.ServletUtil;
import com.vshop.framework.log.event.LogLoginEvent;
import com.vshop.framework.satoken.helper.LoginHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@RequiredArgsConstructor
@Service
public class AuthService {
    private final ApiUserService apiUserService;

    public void afterLogin() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (ObjectUtil.isNull(loginUser)) {
            return;
        }
        // 记录登录日志
        recordLoginLogEvent(loginUser.getTenantId(), loginUser.getUsername(), Const.LoginSuccess, "登录成功");

        // 更新登录信息
        String ip = ServletUtil.getClientIP();
//        apiUserService.updateLoginInfo(loginUser.getUserId(), ip);
        UpdateLoginInfoEvent updateLoginInfoEvent = new UpdateLoginInfoEvent();
        updateLoginInfoEvent.setUserId(loginUser.getUserId());
        updateLoginInfoEvent.setIp(ip);
        SpringContextUtil.publishEvent(updateLoginInfoEvent);
    }

    /**
     * 退出登录
     */
    public void logout() {
        try {
            LoginUser loginUser = LoginHelper.getLoginUser();
            if (ObjectUtil.isNull(loginUser)) {
                return;
            }
//            if (TenantHelper.isEnable() && LoginHelper.isSuperAdmin()) {
//                // 超级管理员 登出清除动态租户
//                TenantHelper.clearDynamic();
//            }
            recordLoginLogEvent(loginUser.getTenantId(), loginUser.getUsername(), Const.Logout, "退出成功");
        } catch (NotLoginException ignored) {
        } finally {
            try {
                StpUtil.logout();
            } catch (NotLoginException ignored) {
            }
        }
    }


    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息内容
     * @return
     */
    public void recordLoginLogEvent(String tenantId, String username, String status, String message) {
        // 封装对象
        LogLoginEvent loginLogEvent = new LogLoginEvent();
        loginLogEvent.setTenantId(tenantId);
        loginLogEvent.setUsername(username);
        loginLogEvent.setStatus(status);
        loginLogEvent.setMessage(message);
        loginLogEvent.setRequest(ServletUtil.getRequest());
        SpringContextUtil.publishEvent(loginLogEvent);
    }

}
